package com.futao.springbootlearn20220224.redis.lua;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * @author futao@gmail.com
 * @date 2022/4/18
 */
@RestController
@RequestMapping("/lua")
public class LuaController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void lua() {
        stringRedisTemplate.getConnectionFactory().getConnection().eval("".getBytes(StandardCharsets.UTF_8),
                ReturnType.BOOLEAN, 1, "".getBytes(StandardCharsets.UTF_8));
        // 先在redis加载script脚本，获取脚本的hash值
        String scriptHash = stringRedisTemplate.getConnectionFactory().getConnection().scriptLoad("".getBytes(StandardCharsets.UTF_8));
        // 通过脚本的hash值来执行这个脚本
        stringRedisTemplate.getConnectionFactory().getConnection().evalSha(scriptHash.getBytes(StandardCharsets.UTF_8),
                ReturnType.BOOLEAN, 1, "".getBytes(StandardCharsets.UTF_8));
    }
}
